package com.feonix.common.view.grid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;

import com.feonix.common.basedao.LikeType;
import com.feonix.common.util.SqlUtil;
import com.feonix.common.util.StringUtil;

public class GridViewSql {

	public static final String SORT_ASC = "ASC";
	public static final String SORT_DESC = "DESC";
	private Map<String, Object> paramMap = new HashMap<String, Object>();
	private GridView gridView;
	private List<String> selectFields = new ArrayList<String>();

	private String table = "";

	private String where = "";

	private String groupBy = "";

	private List<String> order = new ArrayList<String>();

	private String distinct = null;

	private boolean safeCheck = true;

	/**
	 * 获得一个GridViewSql
	 * 
	 * @param paramGridView
	 */
	private GridViewSql(GridView gridView) {
		this.gridView = gridView;
	}

	/**
	 * 获得一个GridViewSql
	 * 
	 * @param gridView
	 * @return
	 */
	public static GridViewSql getInstance(GridView gridView) {
		return new GridViewSql(gridView);
	}

	public Map<String, Object> getParamMap() {
		return this.paramMap;
	}

	/**
	 * 为where语句中的preparedstatement填充值
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public GridViewSql addParam(String key, Object value) {
		this.paramMap.put(key, value);
		return this;
	}

	/**
	 * 为where语句中的preparedstatement填充值
	 * 
	 * @param params
	 * @return
	 */
	public GridViewSql addParams(Map<String, Object> params) {
		if ((params != null) && (params.size() > 0)) {
			this.paramMap.putAll(params);
		}
		return this;
	}

	/**
	 * 为where语句中LIKE 填充值
	 * 
	 * @param key
	 * @param value
	 * @param likeType
	 *            like方式，LR：左右，L：左，R：右
	 * @return
	 */
	public GridViewSql addParam(String key, String value, LikeType likeType) {
		addParam(key, SqlUtil.getLikeValue(value, likeType));
		return this;
	}

	public GridView getGridView() {
		return this.gridView;
	}

	/**
	 * 设置sql语句的select部分
	 * 
	 * @param field
	 *            select的字段
	 * @return
	 */
	public GridViewSql addSelectField(String field) {
		if (StringUtil.isEmpty(field)) {
			return this;
		}
		field = field.trim();
		if (!(this.selectFields.contains(field))) {
			if (field.toUpperCase().startsWith("DISTINCT")) {
				this.distinct = field;

				this.selectFields.add(0, field);
			} else {
				this.selectFields.add(field);
			}
		}

		return this;
	}

	/**
	 * 设置where语句，where语句使用preparedstatement语法方式
	 * 
	 * @param where
	 * @return
	 */
	public GridViewSql setWhere(String where) {
		this.where = where;
		return this;
	}

	/**
	 * 指定表名称
	 * 
	 * @param table
	 * @return
	 */
	public GridViewSql setTable(String table) {
		this.table = table;
		return this;
	}

	/**
	 * 添加order条件
	 * 
	 * @param columnName
	 *            排序字段
	 * @param sortOrder
	 *            排序方式 asc desc
	 * @return
	 */
	public GridViewSql addOrderBy(String columnName, String sortOrder) {
		if (StringUtil.isNotEmpty(columnName)) {
			String str = "ASC";
			if (StringUtil.isNotEmpty(sortOrder)) {
				str = sortOrder;
			}
			this.order.add(columnName + " " + str.toUpperCase());
		}
		return this;
	}

	public String getSelectSql() {
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT ");
		int j = 0;
		for (Iterator<String> it = this.selectFields.iterator(); it.hasNext();) {
			String str = it.next();
			if (j != 0) {
				selectSql.append(",");
			}
			selectSql.append(str);
			++j;
		}
		if (StringUtil.isNotEmpty(this.table)) {
			selectSql.append(" FROM ").append(this.table);
		}
		if (StringUtil.isNotEmpty(this.where)) {
			selectSql.append(" WHERE ").append(this.where);
		}
		if (StringUtil.isNotEmpty(this.groupBy)) {
			selectSql.append(" GROUP BY ").append(this.groupBy);
		}
		if (CollectionUtils.isNotEmpty(this.order)) {
			selectSql.append(" ORDER BY ").append(StringUtil.join(this.order, ","));
		}
		String str = selectSql.toString();
		StringUtil.cleanStringBuffer(new StringBuffer[] { selectSql });
		return str;
	}

	public String getCountSql() {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("SELECT ");
		if (StringUtil.isNotEmpty(this.groupBy))
			stringBuffer.append("COUNT(*) group_count FROM (SELECT 1 group_count_field");
		else if (this.distinct != null)
			stringBuffer.append("COUNT(").append(this.distinct).append(")");
		else {
			stringBuffer.append("COUNT(*)");
		}
		if (StringUtil.isNotEmpty(this.table)) {
			stringBuffer.append(" FROM ").append(this.table);
		}
		if (StringUtil.isNotEmpty(this.where)) {
			stringBuffer.append(" WHERE ").append(this.where);
		}
		if (StringUtil.isNotEmpty(this.groupBy)) {
			stringBuffer.append(" GROUP BY ").append(this.groupBy).append(") group_count");
		}
		String str = stringBuffer.toString();
		StringUtil.cleanStringBuffer(new StringBuffer[] { stringBuffer });
		return str;
	}

	/**
	 * group by 语句
	 * 
	 * @param groupBy
	 */
	public void setGroupBy(String groupBy) {
		this.groupBy = groupBy;
	}

	public boolean isSafeCheck() {
		return this.safeCheck;
	}

	public void setSafeCheck(boolean safeCheck) {
		this.safeCheck = safeCheck;
	}

}
